<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="src || avatar" alt="" class="preview" />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input
          @change="preview"
          type="file"
          accept="imagr /*"
          hidden
          ref="unloadInput"
        />
        <el-button type="primary" icon="el-icon-plus" @click="chooesPhoto"
          >选择图片</el-button
        >
        <el-button
          @click="unloadImg"
          type="success"
          icon="el-icon-upload"
          :disabled="src === ''"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
import { undataImgfoApi } from '@/api/user'
import avatar from '../../assets/images/avatar.jpg'
export default {
  name: 'UserAvatar',
  data () {
    return {
      // 头像的base64格式
      src: '',
      avatar
    }
  },
  methods: {
    chooesPhoto () {
      this.$refs.unloadInput.click()
    },
    preview (e) {
      if (e.target.files.length > 0) {
        console.log('选择的图片', e.target.files[0])
        // 1. 实例化FileReader对象
        const fr = new FileReader()
        // 2. readAsDataURL方法读取图片内容
        fr.readAsDataURL(e.target.files[0])
        // 3.onload事件获取事件内容（base64格式）
        fr.onload = (event) => {
          this.src = event.target.result
        }
      }
    },
    async unloadImg () {
      await undataImgfoApi(this.src)
      this.$message.success('上传成功')
      this.$store.dispatch('user/getUser')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>
